package logic.weapons;

import main.listeners.ListenerContainer;
import main.listeners.ListenerKeeper;

import com.jme.math.FastMath;
import com.jme.scene.Controller;

public class WeaponController extends Controller implements ListenerKeeper {
	
	private static final long serialVersionUID = 1L;
	
	public static final float RELOAD_TIME = 2f;
	
	private float updateTime;
	private Weapon weapon;
	private boolean isReadyToFire;
	private ListenerContainer weaponListeners;
	
	public WeaponController(Weapon weapon) {
		this.weapon = weapon;
		
		weaponListeners = new ListenerContainer(WeaponListener.class);
		
		isReadyToFire = true;
	}
	
	@Override
	public void update(float time) {
		if(!isReadyToFire) {
			updateReloadTime(time);
			if(updateTime == 0f) isReadyToFire = true;
		}
	}
	
	protected void updateReloadTime(float time) {
		updateTime -= FastMath.abs(time * weapon.getWeaponProperties().getShootRate());
		if(updateTime < 0f) updateTime = 0f;
		
		float p = (RELOAD_TIME - updateTime) / RELOAD_TIME * 100f;
		
		weaponListeners.callMethod(WeaponListener.WEAPONRELOADING, new WeaponReloadEvent(weapon, p));
	}
	
	public void weaponFired() {
		isReadyToFire = false;
		updateTime = RELOAD_TIME;
	}
	
	public boolean isReadyToFire() { return isReadyToFire; }
	
	public void addWeaponListener(WeaponListener l) { weaponListeners.addListener(l); }
	
	public float getUpdateTime() { return updateTime; }

	@Override
	public ListenerContainer getListenerContainer(Class<?> listenerClass) {
		if(listenerClass == WeaponListener.class) return weaponListeners;
		return null;
	}
}